package com.gewe.wxChat.netty;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gewe.wxChat.manager.strategy.SanZhiStrategy;
import com.gewe.wxChat.model.dto.MemberInfoDto;
import com.gewe.wxChat.model.dto.gewe.TextCallback;
import com.gewe.wxChat.model.dto.message.MessageDto;
import com.gewe.wxChat.model.entity.WxGroup;
import com.gewe.wxChat.model.entity.WxMember;
import com.gewe.wxChat.service.WxMemberService;
import io.netty.channel.Channel;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Service
public class PushMsgServiceImpl implements PushMsgService {
    @Resource
    private WxMemberService wxMemberService;
    
    @Resource
    private SanZhiStrategy sanZhiStrategy;

    @Override
    public void pushMsgToOne(String deviceWxId, String msg) {
        Channel channel = NettyConfig.getChannel(deviceWxId);
        if (Objects.isNull(channel)) {
            throw new RuntimeException("未连接socket服务器");
        }

        channel.writeAndFlush(new TextWebSocketFrame(msg));
    }

    @Override
    public void pushMsgToAll(String msg) {
        NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
    }

    @Override
    public void pushMsgTofront(String appId,String deviceWxId, TextCallback textCallback) {
        Channel channel = NettyConfig.getChannel(deviceWxId);
        if(channel == null){
            return;
        }
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        String content=textCallback.getContent();
        MessageDto messageDto= new MessageDto();
        messageDto.setContent(textCallback.getContent());
        messageDto.setTime(dateFormatter.format(new Date(textCallback.getCreateTime())));
        //这个信息是群信息，则fromUserName里包含了关键字@chatroom，content里包含了发送者微信id
        String fromUserName=textCallback.getFromUserName();
        if(fromUserName.contains("@chatroom")){
            //从数据库里查群消息和发送者的信息
            String senderWxId=content.split(":", 2)[0];
            MemberInfoDto memberInfoDto=wxMemberService.getIfnfo(senderWxId,fromUserName);
            if(memberInfoDto == null){
                //没有相关信息，拉取群信息
                sanZhiStrategy.getGroupMember(appId,fromUserName);
                memberInfoDto=wxMemberService.getIfnfo(senderWxId,fromUserName);
            }
            //把content中的发言者wxid去掉
            messageDto.setContent(textCallback.getContent().replace(senderWxId+":",""));
            messageDto.setSenderWxId(memberInfoDto.getWxId());
            messageDto.setSenderUserName(memberInfoDto.getWxName());
            messageDto.setSenderRoomId(memberInfoDto.getChatRoomId());
            messageDto.setSenderRoomName(memberInfoDto.getChatRoomName());
        }else {
            LambdaQueryWrapper<WxMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WxMember::getWxId,fromUserName);
            queryWrapper.last("limit 1");
            WxMember wxMember=wxMemberService.getOne(queryWrapper);
            if(wxMember == null){
                return;
            }
            messageDto.setSenderWxId(wxMember.getWxId());
            messageDto.setSenderUserName(wxMember.getNickName());
        }
        //判断senderRoomName空字符串情况
        if( !StringUtils.isEmpty(messageDto.getSenderRoomId())&& StringUtils.isEmpty(messageDto.getSenderRoomName())){
            messageDto.setSenderRoomName("群聊"+messageDto.getSenderRoomId());
        }
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(messageDto)));
    }
}
